#ifndef _COMM_HANDLER_H
#define _COMM_HANDLER_H

extern ConfigFile* logon_config;

class RealmClient;
class RealmHandler;

struct Realm
{
	char* name;
	char* addr;
	ui8 id;
	ui8 icon;
	ui8 color;
	float population;
	map<ui32, ui8> mapping;
};

struct RealmPacketHandler
{
	void (RealmClient::*method)(RealmPacket&);
};

class DLL_EXPORT RealmClient
{
	friend RealmHandler;
	SOCKET m_socket;
	RealmPacketHandler* m_handles;
	Realm* m_realm;
	bool m_isauthed;
	void HandlePacket(RealmPacket* packet);
	RealmClient() : m_isauthed(false)
	{
	}
};

enum AuthResp
{
	RAUTH_OK			= 0x00,
	RAUTH_NOTAUTHED		= 0x01,
};

class DLL_EXPORT RealmHandler : public CThread, public Single<RealmHandler>
{
	fd_set fset;
	SOCKET m_listensocket;
	vector<RealmClient*> m_clients;
	Mutex m_clientlock;
	ui8 m_authhash[16];
	ui8 m_realmid;
public:
	RealmHandler() 
	{
		MD5Hash hash;
		hash.Initialize();
		char* pass = logon_config->GetChar("Authentication", "Passwort");
		hash.UpdateData((ui8*)pass, strlen(pass));
		hash.Finalize();
		memcpy(m_authhash, hash.GetDigest(), 16);
		m_realmid = 1;
	}
	void Loop();
	set<Realm*> m_realms;
	bool CheckAuth(ui8* data)
	{
		return memcmp(m_authhash, data, 16) == 0;
	}
	ui8 GetNewId() { return m_realmid++; }
};

#define sRealmHandler RealmHandler::getSingle()

#endif